<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>综合案例-成绩案例</title>
    <style>
      .red {
        /* background: red; */
        color: red;
      }
      /* .left{
        display: inline;
      }
      .right {
        display: inline;
      } */
    </style>
  </head>
  <body>
    <div id="app" style="margin-left: 150px; margin-top: 150px">
      <div class="left">
        <table border="1" width="500" style="text-align: center">
          <thead>
           <tr>
             <th>编号</th>
             <th>科目</th>
             <th>成绩</th>
             <th>操作</th>
             <th>操作</th>
           </tr>
          </thead>
           <tbody v-if="items.length>0">
             <tr v-for="(item,index) in items" :key="item.id">
               <td>{{index + 1}}</td>
               <td>{{item.name}}</td>
               <td :class="{red:item.score<60}">{{item.score}}</td>
               <td><button @click="del(item.id)">删除</button></td>
               <td><a href="http://www.baidu.com" target="_blank" @click.prevent="del(item.id)">删除</a></td>
             </tr>
           </tbody>
           <tbody v-else>
             <td colspan="5">暂无数据</td>
           </tbody>
           
          <tfoot>
           <tr>
             <td colspan="5">
               总分: {{totalScore}} &nbsp;&nbsp;&nbsp;&nbsp;平均分: {{avgScore}}
             </td>
           </tr>
          </tfoot>
         </table>
      </div>
      <div class="right">
        <td> 
          科目：<input type="text" v-model.trim="subjet" placeholder="请输入科目"> <br>
          分数：<input type="text" v-model.number="score" placeholder="请输入分数"> <br>
          <button @click="add()">添加</button>
        </td>
      </div>
    </div>

    <script src="/js/vue.js"></script>
    <script>
      const app = new Vue({
        el: "#app",
        data: {
          items: [
            { id: 1, name: "语文", score: 20 },
            { id: 2, name: "数学", score: 90 },
            { id: 3, name: "英语", score: 70 },
          ],
          subjet:'',
          score:'',
        },
        methods: {
          del(id) {
            this.items = this.items.filter((item) => item.id !== id);
          },
          add(){
            if(!this.subjet){
              alert('请输入合法的科目');
              return;
            }
            if(this.score.Number){
              alert('请输入合法的分数');
              return;
            }
            this.items.push({id:this.items.length+1,name:this.subjet,score:Number(this.score)});
          },
        },
        computed: {
          totalScore() {
            return this.items.reduce((sum, item) => sum + item.score, 0);
          },
          avgScore() {
            if (this.totalScore === 0) {
              return 0;
            }
            return this.totalScore / this.items.length;
          }
        },
      });
    </script>
  </body>
</html>
